let express = require('express');
let router = express.Router();
let request = require('request');
let fs = require('fs'); 
let base_url=process.env.SERVER_URL;
let qiniu_url=process.env.QINIU_URL;
let socket_port=process.env.SOCKET_PORT;
let API={
	ajax:function(opt){
		//eval(config);
		request({
		    url: base_url + opt.url,
		    method: opt.type||"get",
		    json: true,
		    headers: {"content-type": "application/json",token:opt.token||""},
		    body: opt.data
		}, function(error,res,body) {
		    if (!error && res.statusCode == 200) {
		    	if(opt.success){
		    		opt.success(body);
		    	}	
		    }else{
		    	if(opt.error){
		    		opt.error(body);
		    	}    	
		    }
		}); 
	},
	//排序
	getSort:function(key,desc) {
		return function(a,b){
		　　return desc ? ((parseInt(a[key]) < parseInt(b[key]))?1:((parseInt(a[key]) > parseInt(b[key]))?-1:0)):((parseInt(a[key]) < parseInt(b[key]))?-1:((parseInt(a[key]) > parseInt(b[key]))?1:0));
		}
	},
	//获取全局类型列表
	getState:function(token,callback,error){
		API.ajax({
			url:"/dictionary/all",
			token:token,
			success:function(data){
				callback(data);
			},
			error:function(msg){
				error(msg);
			}
		})
	},
	//获取首页权限
	getHomeAuthority:function(id,token,callback,error){
		API.ajax({
			url:'/indexperm/info',
			data:{casting_id:id},
			token:token,
			success:function(data){
				callback(data)
			},
			error:function(msg){
				if(error){error(err)};
			}
		})
	},
	//是否是数组
	isArray:function(arr) {
		return Object.prototype.toString.apply(arr) === "[object Array]";
	},
	//生成state.js 全局类型列表 文件
	saveState:function(data,callback){
		var state={};
		var list=data.list;
		for(var i=0;i<list.length;i++){
			if(state[list[i].dic_parent]){
				state[list[i].dic_parent].push({
					name:list[i].dic_name,
					id:list[i].dic_id
				})
			}else{
				state[list[i].dic_parent]=[
					{
						name:list[i].dic_name,
					    id:list[i].dic_id
					}
				]
			}
		}
		fs.writeFileSync("./public/js/base/state.js",'var state=' + JSON.stringify(state),{encoding:'utf-8'},function(){
			
		})
		callback(JSON.stringify(state));
		//console.log(JSON.stringify(state))
	},
	//处理menu格式
	transformTozTreeFormat:function(sNodes,childKey,type) {
		//排序
		var arr=sNodes;
		var sNodes=arr.sort(API.getSort('rank',false));
	    var i,l,
	    key = 'id',
	    parentKey = 'pid',
	    childKey = childKey||'sub_menu';
	    if (!key || key=="" || !sNodes) return [];
	    if (sNodes) {
	        var r = [];
	        var m=[];
	        var tmpMap = {};
	        for (i=0, l=sNodes.length; i<l; i++) {
	            tmpMap[sNodes[i][key]] = sNodes[i];
	        }
	        for (i=0, l=sNodes.length; i<l; i++) {
	        	if(type=='index'){
	        		if(sNodes[i].selected!=1){
	        			continue;
	        		}
	        	}else{
	        		if(sNodes[i].type==2||sNodes[i].type==3||sNodes[i].type==4||sNodes[i].selected!=1){
	        			continue;
	        		}
	        	}
	            if (tmpMap[sNodes[i][parentKey]] && sNodes[i][key] != sNodes[i][parentKey]) {
	                if (!tmpMap[sNodes[i][parentKey]][childKey])
	                    tmpMap[sNodes[i][parentKey]][childKey] = [];
	                tmpMap[sNodes[i][parentKey]][childKey].push(sNodes[i]);
	            } else {
	                r.push(sNodes[i]);
	            }
	        }
	        return r.sort(API.getSort('rank',false));
	    }else {
	        return [sNodes];
	    }
	},
	//处理列，按钮
	transformToFildsFormat:function(sNodes){
		API.feldsTree=[];
		API.btnsTree=[];
		var felds={};
		var btns={};
        for (i=0, l=sNodes.length; i<l; i++) {
        	if(sNodes[i].type==2&&sNodes[i].selected==1){
        		API.btnsTree.push(sNodes[i]);
        	}
        	if(sNodes[i].type==3&&sNodes[i].selected==1){
        		API.feldsTree.push(sNodes[i]);
        	}
	    }   
	   	var f=API.feldsTree;
		var b=API.btnsTree;
		for(var i=0,l=b.length;i<l;i++){
			var url_0=b[i]['html_path'].split("?")[0];
			var url_1=b[i]['html_path'].split("?")[1];
			b[i].keyURL=url_0;
			b[i].keyword=url_1;
			if(!API.isArray(btns[url_0])){
				btns[url_0]=[];
				btns[url_0].push(b[i])
			}else{
				btns[url_0].push(b[i])
			}
		}

		for(var i=0,l=f.length;i<l;i++){
			var url_0=f[i]['html_path'].split("?")[0];
			var url_1=f[i]['html_path'].split("?")[1];
			f[i].keyURL=url_0;
			f[i].keyword=url_1;
			if(!API.isArray(felds[url_0])){
				felds[url_0]=[];
				felds[url_0].push(f[i])
			}else{
				felds[url_0].push(f[i])
			}
		}
		return {
			btns:btns,
			felds:felds
		};
	},
	//首页权限拆分左右列
	homeMsgSplit:function(json){
		var left=[];
		var right=[];
		for(var i=0;i<json.length;i++){
			if(json[i].site=="left"){
				left.push(json[i]);
				continue;
			}
			if(json[i].site=="right"){
				right.push(json[i]);
				continue;
			}
		}
		return {
			left:left,
			right:right
		}

	}
};
//登录
router.post('/login',function(req, res, next){
	API.ajax({
		url:'/user/login',
		data:req.body,
		type:"post",
		success:function(data){
			if(data.code==1){
				res.send({code:500,msg:data,url:base_url});
				return;
			}
		    var message=JSON.parse(JSON.stringify(data.data));
		    delete message.menu; 	
			if(data.code==0){
				req.session.loginMsg=JSON.stringify(message);
				if(!data.data.menu.msg){//菜单权限
					var menu=API.transformTozTreeFormat(data.data.menu);
					req.session.menu=menu;
					var zNodes_rols=API.transformToFildsFormat(data.data.menu);
					req.session.btns=zNodes_rols.btns;
					req.session.felds=zNodes_rols.felds;
				}
				var cast_ids=(data.data.user_id==1?'admin':data.data.cast_ids);//判断是否是超管
				if(cast_ids){//首页权限
					API.getHomeAuthority(cast_ids,data.data.token,function(indexMsg){
						var obj=API.homeMsgSplit(API.transformTozTreeFormat(indexMsg.list,'children','index'));
						req.session.index_left=obj.left;
						req.session.index_right=obj.right;
						(obj.left.length==0&&obj.right.length==0)?req.session.index_msg=null:req.session.index_msg=true;	
						res.send(data);
					})	
				}else{
					res.send(data);
				}
				
						
			}else{
				res.send(data);
			}
		},
		error:function(err){
			console.log(err)
			res.send({code:500,msg:err,url:base_url});
		}
	})
});
//退出登录
router.post('/logout', function (req, res, next) {
    req.session.destroy();
    res.send({
    	code:0
    });
});
//更新state
router.post('/getState', function (req, res, next) {
	API.getState(JSON.parse(req.session.loginMsg).token,function(r){
		API.saveState(r,function(data){
			res.send({
		    	code:0,
		    	data:data
		    });
		});	
	},
	function(err){
		res.send({
	    	code:500,
	    	msg:err
	    });
	});
});

//创建帮助文档
router.post('/createHelp', function (req, res, next) {
	var list=JSON.parse(req.body.data);
	var obj={};
	for(var i=0;i<list.length;i++){
		obj[list[i]['html_path']]=list[i];
	}
	fs.writeFileSync("./public/js/base/help.js",'var HELP=' + JSON.stringify(obj),{encoding:'utf-8'},function(){
	   
	})
	res.send({
	   code:0,
	   msg:'创建文件成功'
	 });
});



router.API=API;
module.exports = router;
